package com.example.yimai.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTUtil {

    // 签名秘钥
    // yimai AEC加密
    private static final String SECRET = "U2FsdGVkX19zvnBXAtQIKRvb8hFU5b+WJsNV6QoQNSQ=";

    // token过期时间 一小时
    private final Long expire = 1000 * 60 * 60L;

    private SecretKey getSigningKey(){
        byte[] keyBytes = SECRET.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }


    public boolean validateToken(String token){
        try {
            Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public String generateToken(String id, String loginName, Integer type){
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("loginName", loginName);
        claims.put("type", type);

        return createToken(claims);
    }

    private String createToken(Map<String ,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(getSigningKey())
                .compact();
    }

    public Claims getClaimsFromToken(String token){
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public Long getExpiration(){
        return expire;
    }


    public String getId(String token){
        Claims claims = getClaimsFromToken(token);
        return (String) claims.get("id");
    }

    public String getLoginName(String token){
        Claims claims = getClaimsFromToken(token);
        return (String) claims.get("loginName");
    }

    public Integer getType(String token){
        Claims claims = getClaimsFromToken(token);
        return (Integer) claims.get("type");
    }
}
